<template>
  <el-button plain @click="dialogTableVisible = true" type="success">添加</el-button>
  <el-table :data="tableData" style="width: 100%" border>
    <el-table-column fixed prop="" type="index" label="编号" width="100" />
    <el-table-column prop="roleName" label="角色名称" width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="openRoleUserDialog(scope.row)">{{ scope.row.roleName
          }}</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="crearName" label="创建人" width="120" />
    <el-table-column prop="crearTime" label="创建时间" width="100">
      <template #default="scope">
        <span>{{ moment(scope.row.crearTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" width="100" />
    <el-table-column prop="updateTime" label="修改时间" width="100">

      <template #default="scope">
        <span v-if="scope.row.updateTime == null"></span>
        <span v-else>{{ moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作列" min-width="100">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="open(scope.row.id)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="Updat(scope.row)">修改</el-button>
        <el-button link type="primary" size="small" @click="fenpei(scope.row)">分配人员</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加 -->
  <el-dialog v-model="dialogTableVisible" title="添加" width="800">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="角色名：" prop="roleName">
        <el-input v-model="ruleForm.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改 -->
  <el-dialog v-model="dialogTableVisible1" title="修改" width="800">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="角色名：" prop="roleName">
        <el-input v-model="ruleForm.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForms">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 分配人员 -->
  <el-dialog v-model="dialogTableVisible2" :title="'请设置【' + chuanroleName + '】角色的员工'" width="800">
    <el-row>
      <el-col :span="12">
        <!-- 部门树 -->
        <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data" :props="defaultProps"
          default-expand-all @node-click="nodeclick" />
      </el-col>
      <el-col :span="12">
        <!-- 用户选择 -->

        <!-- <el-tree style="max-width: 600px" :props="defaultProps1" :data="data1" lazy show-checkbox v-for="item in data1"
          :value="item.id"></el-tree> -->
        <!-- <el-tree style="max-width: 600px" :data="data1" v-model="roleuser" show-checkbox  :node-key="defaultProps1.id"  :props="defaultProps1"/> -->
        <el-checkbox-group v-model="roleuser">
          <el-checkbox v-for="item in data1" :value="item.id">
            {{ item.userName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogTableVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="CreatedeRoleName()">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 分配人员 -->
  <!-- <el-dialog v-model="dialogTableVisible3" :title="''" width="800"> -->
  <el-dialog v-model="dialogTableVisible3" :title="'请设置【' + setrolenames + '】角色的'" width="500">
    <table>
      <tr v-for="item in getrolename.usernames">
        <td>
          {{ item.userName }}
        </td>
        <td @click="delroleuser(item.id)">
          ×
        </td>
      </tr>
      <tr @click="openRoleUser()"
        style="width: 10px; height: 25px;border: none;font-size: 40px;margin-top: 2px;font-weight: 600;">+

      </tr>
    </table>
    <el-buttou type="primary" @click="">提交</el-buttou>
    <!-- <el-row>
      <el-col>
        <table>
          <tr v-for="item in getrolename.username">
            <td>
              {{ item.userName }}
            </td>
            <td @click="delroleuser(item.id)">×</td>
          </tr>
          <tr @click="openRoleUser()" style="width: 10px; height: 25px;border: none;font-size: 40px;margin-top: 2px;font-weight: 600;">+</tr>
        </table>
      </el-col>
    </el-row> -->
    <!-- <el-button link type="primary" size="small" @click="CreatedeRoleName()">保存</el-button> -->
  </el-dialog>
  <!-- 分配员工弹窗（只多选用户，无部门树） -->
  <!-- <el-dialog v-model="assignDialogVisible" title="分配员工" width="400">
    <el-checkbox-group v-model="selectedUserIds">
      <el-checkbox
        v-for="item in allUserList"
        :key="item.id"
        :label="item.id"
      >{{ item.userName }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="assignDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveAssign">保存</el-button>
    </template>
  </el-dialog> -->
</template>

<script lang="ts" setup>
import axios from 'axios';
import moment from 'moment';
import { useRouter } from 'vue-router'
const router = useRouter();
import { onMounted, ref } from 'vue';
import https from '../../http/AxiosHelper';

const handleClick = () => {
  console.log('click')
}

const jieshuo = ref({
  "id": '',
  "roleName": "",
  "crearName": "",
  "crearTime": "",
  "updateName": "",
  "updateTime": ''
})

const getJie = (row: any) => {
  jieshuo.value = row
}

const tableData = ref([]);
const getData = () => {
  https.get("api/Role/ShowRole").then(res => {
    tableData.value = res.data.data
  })
}
onMounted(() => {
  getData();
})
//弹框
const dialogTableVisible = ref(false);
const dialogTableVisible1 = ref(false);
const dialogTableVisible2 = ref(false);
const dialogTableVisible3 = ref(false);
import { reactive } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";


const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  "roleName": ""
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive({
  roleName: [
    { required: true, message: "用户名称不能为空", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      https.post("api/Role/AddRole", ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg)
          dialogTableVisible.value = false
          ruleForm.roleName = '';
          getData();
        }
        else {
          ElMessage.error(res.data.msg)
        }
      })
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogTableVisible.value = false
};
// 删除
import { ElMessageBox } from 'element-plus'

const open = (id: any) => {
  ElMessageBox.confirm(
    '确定删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      https.get("api/Role/DelRole", {params:{ id: id }}).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          getData();
        }
        else {
          ElMessage.error(res.data.msg);
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}
//修改
const Updat = (row: any) => {
  dialogTableVisible1.value = true;
  Object.assign(ruleForm, row);
}
const submitForms = () => {
  https.post("api/Role/UpdateRole", ruleForm).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      dialogTableVisible1.value = false;
      getData();
    }
    else {
      ElMessage.error(res.data.msg)
    }
  })
};
//分配人员
const chuanroleName = ref('');
const setrolenames = ref('');
const fenpei = (row: any) => {
  dialogTableVisible2.value = true
  chuanroleName.value = row.roleName
  getrolename.roleId = row.id

  GetRoleUserId();
}
//树形
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
import { watch } from 'vue'
interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
  children: 'children',
  label: 'label',
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

const nodeclick = (x: any) => {
  getShuUser(x.id)
}
const data: Tree[] = [
  {
    id: 0,
    label: '请选择部门',
    children: [
      {
        id: 1,
        label: 'IT信息部',
      },
      {
        id: 2,
        label: '人力资源部',
      },
      {
        id: 3,
        label: '财务部',
      },
      {
        id: 4,
        label: '销售部',
      },
    ],
  },
]
//用户树形活值
const defaultProps1 = {
  id: 'id',
  label: 'userName'
}
const data1 = ref<any>([])
const getShuUser = (id: number) => {

  https.get("api/User/GetDel", {
    params: { DeionId: id }
  }).then(res => {
    if (res.data.code === 200) {
      console.log(res.data);

      data1.value = res.data.data
      console.log('部门用户列表:', data1.value)
    }
  })
}
const roleuser = ref([]);
const darry = ref([])
const getrolename = reactive({
  "userId": [],
  "roleId": 0,
  usernames: [{
    "id": '',
    "userName": "",
  }]
  // username: [] as { id: number, userName: string }[]
})
//分配
const CreatedeRoleName = () => {
  getrolename.userId = roleuser.value;
  https.post("api/UserRole/AddUserRole", getrolename).then(res => {
    if (res.data.code = 200) {
      ElMessage.success(res.data.msg);
      dialogTableVisible2.value = false
      console.log(getrolename.userId);
      
      getData();
    }
    else {
      ElMessage.error(res.data.msg);
    }
  })
}
//根据角色id反填
const GetRoleUserId = () => {
  https.get("api/UserRole/GetUserRole", { params: { RoleId: getrolename.roleId } }).then(res => {
    roleuser.value = res.data.data.map((item: any) => Number(item.id));
    getrolename.usernames = res.data.data;

    console.log(roleuser.value);
  })
}
//角色名称、
const openRoleUserDialog = (row: any) => {
  dialogTableVisible3.value = true;
  chuanroleName.value = row.roleName
  getrolename.roleId = row.id//是主键的id
  setrolenames.value = row.roleName
  GetRoleUserId();

}
//删除
const delroleuser = (id: any) => {
  https.post("api/UserRole/DelUserRole", {
    "userId": id,
    "roleId": getrolename.roleId,
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      GetRoleUserId();
    }
    else {
      ElMessage.error(res.data.msg);
    }
  });
}
//+
const openRoleUser = () => {

  dialogTableVisible2.value = true
  GetRoleUserId();

}
</script>
